//
//  CitysViewController.m
//  ZhuanZuBao
//
//  Created by bchy on 2020/8/28.
//  Copyright © 2020 戴伟. All rights reserved.
//

#import "CitysViewController.h"
#import "FMDatabase.h"
#import "CityModel.h"
#import "CityLocateCell.h"
#import "CityHotCell.h"
#import <AMapLocationKit/AMapLocationKit.h>

@interface CitysViewController ()<CityHotCellDelegate, AMapLocationManagerDelegate>

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSArray *hotCity;
@property (nonatomic, strong) NSArray *sectionArr;

@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, copy) NSString *currentCity;

@end

@implementation CitysViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择城市";
    _hotCity = @[@"合肥",@"福州",@"长沙",@"成都",@"南昌"];
    
    NSMutableArray <CityModel *> *cityArr = [self dc_getDBArrayWithdbArray];

    NSMutableArray *finalArr = [NSMutableArray array];
    _sectionArr = @[@"定位",@"热门",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U"
    ,@"V",@"W",@"X",@"Y",@"Z"];
    for (NSString *section in _sectionArr) {
        NSDictionary *dict = @{
            @"section": section,
            @"arr": [NSMutableArray array]
        };
        [finalArr addObject:dict];
    }
    for (CityModel *city in cityArr) {
        NSString *firstLetter = [[city.pinyin substringToIndex:1] uppercaseString];
        for (NSDictionary *dict in finalArr) {
            if ([dict[@"section"] isEqualToString:firstLetter]) {
                NSMutableArray *arr = dict[@"arr"];
                [arr addObject:city];
                break;
            }
        }
    }

    _dataArr = [NSMutableArray arrayWithArray:finalArr];
    [self.tableView reloadData];
    
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    self.locationManager.locationTimeout =2;
    self.locationManager.reGeocodeTimeout = 2;
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            if (error){
                NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                [MBProgressHUD showError:@"定位失败" toView:nil];
                if (error.code == AMapLocationErrorLocateFailed){
                    return;
                }
            }else{
                if (regeocode){
                    NSLog(@"reGeocode:%@", regeocode);
                    NSString *city = regeocode.city;
                    if (!city) {
                        city = @"未知地区";
                    }
                    if ([city hasSuffix:@"市"]) {
                        city = [city substringToIndex:city.length-1];
                    }
                    
                    self.currentCity = city;
                    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                    [self.locationManager stopUpdatingLocation];
                }
            }
            
        }];
}




#pragma mark - 读取数据
- (NSMutableArray *)dc_getDBArrayWithdbArray
{
    NSString *table = [NSString stringWithFormat:@"select * from %@",@"cities"];
    NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"china_cities_v2" ofType:@"db"];
    FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
    if (![database open]) return 0;
    // 查找表 AllTheQustions
    FMResultSet *resultSet = [database executeQuery:table];
    resultSet = [database executeQuery:table];
    
    NSMutableArray *array = [NSMutableArray array];
    // 循环逐行读取数据resultSet next
    while ([resultSet next])
    {
        CityModel *city = [[CityModel alloc] init]; //给模型赋值
        
        city.name = [resultSet stringForColumn:@"c_name"];
        city.pinyin = [resultSet stringForColumn:@"c_pinyin"];
        city.code = [resultSet stringForColumn:@"c_code"];
        city.province = [resultSet stringForColumn:@"c_province"];
        
        [array addObject:city];
    }
    
    [database close]; //关闭
    return array;
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableViw{
    return _sectionArr;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArr.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return 1;
    }
    NSDictionary *dict = _dataArr[section];
    NSMutableArray *arr = dict[@"arr"];
    return arr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 64;
    }
    if (indexPath.section == 1) {
        return 138;
    }
    return 44;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSDictionary *dict = _dataArr[section];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, DEVICE_SCREEN_WIDTH, 44)];
    label.backgroundColor = BGCOLOR;
    if (section == 0) {
        label.text = @"    定位城市";
    }else if (section == 1){
        label.text = @"    热门城市";
    }else{
        label.text = [NSString stringWithFormat:@"    %@", dict[@"section"]];
    }
    
    label.textColor = BLACKTEXTCOLOR;
    label.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    return label;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        CityLocateCell *cell = [CityLocateCell cellWithTableView:tableView];
        if (_currentCity) {
            [cell setCurrentCity:_currentCity];
        }
        return cell;
    }
    if (indexPath.section == 1) {
        CityHotCell *cell = [CityHotCell cellWithTableView:tableView];
        cell.delegate = self;
        return cell;
    }
    NSDictionary *dict = _dataArr[indexPath.section];
    NSMutableArray *arr = dict[@"arr"];
    CityModel *city = arr[indexPath.row];
    UITableViewCell *cell = [UITableViewCell new];
    cell.textLabel.text = city.name;
    cell.textLabel.textColor = BLACKTEXTCOLOR;
    cell.selectionStyle = UITableViewCellAccessoryNone;
    cell.textLabel.font = [UIFont systemFontOfSize:14];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //选择的是定位城市
        if (_currentCity) {
            if (self.chooseCityBlock) {
                self.chooseCityBlock(_currentCity);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
        return;
    }
    NSDictionary *dict = _dataArr[indexPath.section];
    NSMutableArray *arr = dict[@"arr"];
    CityModel *city = arr[indexPath.row];
    
    if (self.chooseCityBlock) {
        self.chooseCityBlock(city.name);
    }
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)selectCity:(NSString *)city{
    if (self.chooseCityBlock) {
        self.chooseCityBlock(city);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

@end
